package com.example.Controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.Controller.utils.R;
import com.example.domain.Employee;
import com.example.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;


@CrossOrigin
@RestController
@RequestMapping("/books")
public class EmployeeController {

    @Autowired
    private IEmployeeService bookService;

    @GetMapping
    public R getAll(){
        return new R(true,bookService.list()) ;
    }


    //增加
    //@ResponseBody注解表示该方法的返回结果直接写入HTTP response body中  用来返回Json数据
    @PostMapping
    public R save(@RequestBody Employee employee) throws IOException {
//        R r = new R();
//        boolean flag = bookService.save(book);
//        r.setFlag(flag);
//        if (employee.getName().equals("123")) throw new IOException();
        boolean flag = bookService.save(employee);
        return new R(flag,flag ? "添加成功！！！" : "添加失败！！！");
    }


    //修改
    @PutMapping
    public R update(@RequestBody Employee book){
        return new R(bookService.updateById(book));
    }


    //删除
    //通过id来查询
    @DeleteMapping("{id}")
    public R delete(@PathVariable  int id){
        return new R(bookService.removeById(id));
    }

    //查找
    @GetMapping("{id}")
    public R getById(@PathVariable int id){

        return  new R(true,bookService.getById(id));
    }

//    @GetMapping("{currentPage}/{pageSize}")
//    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize){
//
//        IPage<Book> page = bookService.getPage(currentPage, pageSize);
//        //如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
//        if(currentPage > page.getPages()){
//             page = bookService.getPage((int)page.getPages(), pageSize);
//        }
//
//
//        return  new R(true,page);
//    }


    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Employee employee){
        IPage<Employee> page = bookService.getPage(currentPage, pageSize,employee);
        //如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if(currentPage > page.getPages()){
            page = bookService.getPage((int)page.getPages(), pageSize,employee);
        }
        return  new R(true,page);
    }

}
